import 'package:bilibili/http/core/hi_error.dart';
import 'package:bilibili/http/core/hi_net_adapter.dart';
import 'package:bilibili/http/request/base_request.dart';
import 'package:http/http.dart' as http;

class HttpAdapter extends HiNetAdapter {
  Future<HiNetResponse<T>> send<T>(BaseRequest request) async {
    http.Response? response;
    var error;

    var client = http.Client();

    try {
      if (request.httpMethod() == HttpMehtod.GET) {
        response = await client.get(request.url(), headers: request.header);
      } else if (request.httpMethod() == HttpMehtod.POST) {
        response = await client.post(request.url(),
            headers: request.header, body: request.params);
      } else if (request.httpMethod() == HttpMehtod.DELETE) {
        response = await client.delete(request.url(),
            headers: request.header, body: request.params);
      }
    } catch (e) {
      error = e;
    } finally {
      client.close();
    }

    if (error != null) {
      throw HiNetError(response?.statusCode ?? -1, error.toString(),
          data: buildRes(response, request));
    }

    return buildRes(response, request);
  }

  // 构建HiNetResponse
  Future<HiNetResponse<T>> buildRes<T>(
      http.Response? response, BaseRequest request) {
    return Future.value(HiNetResponse(
        data: response?.body as T,
        request: request,
        statusCode: response?.statusCode));
  }
}
